package myJs.user.centrifuge

import java.math.BigInteger
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.Utils._
import myJs.myPkg._
import org.scalajs.dom.Element
import org.scalajs.dom
import org.scalajs.dom._
import org.w3c.dom.html.HTMLSelectElement
import scalatags.Text.all.{value, _}

import scala.scalajs.js.JSConverters._
import myJs.tool.Tool._
import org.scalajs.dom.raw.HTMLFormElement

import scala.scalajs.js.JSON
import myJs.myPkg.jquery._
import org.scalajs.dom.ext.Ajax

import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Try
import myJs.Implicits._
import myJs.tool.Tool
import shared.VarTool

import scala.collection.immutable.SeqMap
import scala.scalajs.js.Dynamic.{global => g}

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("NewMission")
object NewMission {

  val formId = "form"

  @JSExport("init")
  def init = {
    Tool.fileInput
    Tool.popover
    refreshDb
    registerEvent

    getCpuNum { cpuNum =>
      bootStrapValidator(cpuNum)
      $("#form").bv.revalidateField("missionName")
    }

  }

  def refreshDb = {
    val inputName = "db"
    val map = VarTool.dbMap
    val array = map.map { case (id, text) =>
      js.Dictionary("text" -> text, "id" -> id)
    }
    val options = Select2Options.dictData(array.toJSArray).multiple(false)
    Tool.getInputByName(inputName).mySelect2(options)
  }

  def registerEvent = {
    $(document.body).on("click", s".myRun", "", (y: Element) => {
      myRun
    })
  }

  def myRun = {
    val bv = $("#form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val formData = new FormData(document.getElementById("form").toHTMLFormElement)
      val element = div(id := "content",
        span(id := "info", "文件上传中",
          span(id := "progress")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.icon(16).shade(0.01).time(20000000)
      val index = layer.msg(element, layerOptions)
      val url = g.jsRoutes.controllers.CentrifugeController.newMission().url.toString
      val xhr = new XMLHttpRequest
      xhr.open("post", url)
      xhr.upload.onprogress = progressHandlingFunction
      xhr.onreadystatechange = (e) => {
        if (xhr.readyState == XMLHttpRequest.DONE) {
          val data = xhr.response
          val rs = JSON.parse(data.toString).toJDJAn
          layer.close(index)
          val valid = rs("valid").toB
          if (valid) {
            window.location.href = g.jsRoutes.controllers.CentrifugeController.missionManageBefore().url.toString
          } else {
            g.swal("Error", rs.myGet("message"), "error")
          }
        }
      }
      xhr.send(formData)
    }
  }

  def getCpuNum(f: Int => Unit) = {
    val url = g.jsRoutes.controllers.CentrifugeController.getCpuNum().url.toString
    Ajax.get(url = s"${url}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText
      val cpuNum = rs.toInt
      f(cpuNum)
    }
  }

  def bootStrapValidator(cpuNum: Int) = {
    val url = g.jsRoutes.controllers.CentrifugeController.missionNameCheck().url.toString
    val maxNumber = Double.MaxValue
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "missionName" -> {
          val info = "任务名"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空!"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${info}已存在!",
                "url" -> url,
                "type" -> "POST",
                "delay" -> 1000
              ),
            )
          )
        },
        "fq1File" -> {
          val info = "fq1文件"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "file" -> js.Dictionary(
                "message" -> s"${info}格式不正确（*.fq,*.fastq）！",
                "extension" -> "fq,fastq",
              ),
            )
          )
        },
        "fq2File" -> {
          val info = "fq2文件"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "file" -> js.Dictionary(
                "message" -> s"${info}格式不正确（*.fq,*.fastq）！",
                "extension" -> "fq,fastq",
              ),
            )
          )
        },
        "trim5" -> {
          val info = "trim5"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "integer" -> js.Dictionary(
                "message" -> s"${info}必须为自然数！",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> maxNumber,
                "message" -> s"${info}必须大于等于0",
              ),
            )
          )
        },
        "trim3" -> {
          val info = "trim3"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "integer" -> js.Dictionary(
                "message" -> s"${info}必须为自然数！",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> maxNumber,
                "message" -> s"${info}必须大于等于0",
              ),
            )
          )
        },
        "threadNum" -> {
          val info = "线程数"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "integer" -> js.Dictionary(
                "message" -> s"${info}必须为整数！",
              ),
              "between" -> js.Dictionary(
                "min" -> 1,
                "max" -> maxNumber,
                "message" -> s"${info}必须大于0且小于等于${cpuNum}(服务器可用最大cpu)！",
              ),
            )
          )
        },
      )
    )
    g.$("#form").bootstrapValidator(dict)

  }

}
